<template>
  <basic-container>
    <avue-crud :option="option" v-model:search="search" v-model:page="page" v-model="form" :table-loading="loading"
      :data="data" :permission="permissionList" :before-open="beforeOpen" ref="crud" @row-update="rowUpdate"
      @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger" icon="el-icon-delete" plain v-if="permission.expert_delete" @click="handleDelete">删 除
        </el-button>
        <!-- <el-button type="warning" plain icon="el-icon-download" @click="handleExport">导 出
        </el-button> -->
      </template>
      <template #menu="row">
        <el-button type="primary" link icon="el-icon-user" @click="handleUser(row)">分配用户
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="分配用户" append-to-body v-model="showUser" width="1200px">
      <avue-crud :option="userOption" :table-loading="userLoading" :data="userData" ref="userCrud" v-model="userForm"
        :permission="permissionList" :before-open="beforeOpenUser" @row-del="rowDelUser" @row-save="rowSaveUser"
        @search-change="searchChangeUser" @search-reset="searchResetUser" @selection-change="selectionChangeUser"
        @current-change="currentChangeUser" @size-change="sizeChangeUser" @refresh-change="refreshChangeUser"
        @on-load="onLoadUser">
        <template #menu-left>
          <el-button icon="el-icon-delete" @click="cancelUser" plain>移除
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>

</template>

<script>
import { getExpertList, getDetail } from "@/api/position/expert";
import {
  add,
  getList,
  getRole,
  getRoleTreeById,
  grant,
  grantTree,
  remove,
  update,
  getUserList,
  addUserList,
  removeUserList,
  getUserPage
} from '@/api/system/role';
import option from "@/option/position/expert";
import { mapGetters } from "vuex";
import { exportBlob } from "@/api/common";
import { getToken } from '@/utils/auth';
import { downloadXls } from "@/utils/util";
import { dateNow } from "@/utils/date";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],
      data_source: [],
      // 子表
      showUser: false,
      roleId: '',
      userOption: {
        height: 'auto',
        calcHeight: 140,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        editBtn: false,
        viewBtn: false,
        menuWidth: 120,
        delBtnText: '移除',
        addBtnText: '添加',
        column: [
          {
            label: '登录账号',
            prop: 'userIds',
            hide: true,
            type: 'select',
            span: 24
          },
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false,
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false,
          },
          {
            label: '密级',
            prop: 'securityName',
            slot: true,
            display: false,
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false,
          },
          {
            label: '状态',
            prop: 'statusName',
            slot: true,
            display: false,
          },
          {
            label: '添加时间',
            prop: 'createTime',
            slot: true,
            display: false,
          },
        ],
      },
      userLoading: true,
      userData: [],
      userForm: {},
      userPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      userQuery: {},
      userSelectionList: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.expert_add, false),
        viewBtn: this.validData(this.permission.expert_view, false),
        delBtn: this.validData(this.permission.expert_delete, false),
        editBtn: this.validData(this.permission.expert_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted(){
    this.getUserPage()
  },
  methods: {
    rowSave(row, done, loading) {
      row.parentId = '1818485897055547393';
      row.parentName = '专家角色';
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleExport() {
      let downloadUrl = `/position/expert/export-expert?${this.website.tokenHeader}=${getToken()}`;
      const {
        name,
        note,
      } = this.query;
      let values = {
        name_like: name,
        note_like: note,
      };
      this.$confirm("是否导出数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
          downloadXls(res.data, `专家${dateNow()}.xlsx`);
          NProgress.done();
        })
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        name,
        note,
      } = this.query;

      let values = {
        name_like: name,
        note_like: note,
      };
      //page.currentPage, page.pageSize
      getExpertList(name).then(res => {
        const data = res.data.data;
        this.page.total = data.length;
        this.data = data;
        this.loading = false;
        this.selectionClear();
      });
    },
    async loadData(currentPage, pageSize, userName) {
      if (this.data_source.length == 0) {
        let dataList_res = await getExpertList(userName);
        this.data_source = dataList_res.data.data;
      }
      let start = (currentPage - 1) * pageSize;
      let end = start + pageSize;
      this.page.total = this.data_source.length;
      this.data = this.data_source.slice(start, end);
      this.loading = false;
      this.selectionClear();
    },


    //分配用户
    // 子表
    handleUser({ row }) {
      this.roleId = row.id
      this.showUser = true
      this.onLoadUser(this.userPage)
    },
    beforeOpenUser(done, type) {
      if (['add', 'edit'].includes(type)) {

      }
      done();
    },
    cancelUser(){
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeUserList(this.roleId, this.userSelectionList.map(item=>item.id).join(','));
        })
        .then(() => {
          this.onLoadUser(this.userPage);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    rowDelUser(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeUserList(this.roleId, row.id);
        })
        .then(() => {
          this.onLoadUser(this.userPage);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    rowSaveUser(row, done, loading) {
      addUserList(this.roleId, row.userIds).then(
        () => {
          this.onLoadUser(this.userPage);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    userSelectionClear() {
      this.userSelectionList = [];
      this.$refs.userCrud.toggleSelection();
    },
    searchChangeUser(params, done) {
      this.userQuery = params;
      this.userPage.currentPage = 1;
      this.onLoadUser(this.userPage, params);
      done();
    },
    searchResetUser() {
      this.userQuery = {};
      this.onLoadUser(this.userPage);
    },
    selectionChangeUser(list) {
      this.userSelectionList = list;
    },
    currentChangeUser(currentPage) {
      this.userPage.currentPage = currentPage;
    },
    sizeChangeUser(pageSize) {
      this.userPage.pageSize = pageSize;
    },
    refreshChangeUser() {
      this.onLoadUser(this.userPage, this.userQuery);
    },
    onLoadUser(page, params = {}) {
      this.userLoading = true;
      params.roleId = this.roleId
      getUserList(page.currentPage, page.pageSize, Object.assign(params, this.userQuery)).then(res => {
        this.userData = res.data.data.records;
        this.userPage.total = res.data.data.total
        this.userLoading = false;
        this.userSelectionClear();
      });
    },
    getUserPage(){
      getUserPage(1, 10000).then(res => {
        this.userOption.column[0].dicData = res.data.data.records.map(item => {
          return {
            label: `账号：${item.account}，姓名：${item.realName}`,
            value: item.id
          }
        })
      })
    },
  }
};
</script>

<style></style>
